import axios, {AxiosInstance, AxiosResponse} from 'axios';
import {userStore} from "../store/user";
import pinia from "../pinia";
import {sys} from "../model/system";
import {ElMessage} from "element-plus";

const Axios: AxiosInstance = axios.create({
    baseURL: 'http://127.0.0.1:2024',
    timeout: 5000,
})

Axios.interceptors.request.use(function (request) {
    request.headers=GetHeaders()
    return request
})

Axios.interceptors.response.use(function (response:AxiosResponse<sys.Result<any>>) {

        return response
    }, function (error) {
        if (error.response.data!==null){
            let result: sys.Result<any> = error.response.data
            let msg=''
            if (result.msg!==''){
                msg+=result.msg
            }
            if(result.err!==''){
                msg+=','+result.err
            }
            ElMessage({
                type:'error',
                message:msg
            })
        }
        return error.response34
    })

export function GetHeaders(): any {
    let token: string = GetToken()
    let header: any = {}

    // 添加 token 头
    if (token !== '') {
        header.Authorization = token
    }
    return header
}

function GetToken(): string {
    let token: string = ''
    let store = userStore(pinia);
    let t = store.userInfo.token
    if (t !== '') {
        token = 'Bearer ' + t
    }
    return token
}

export default Axios
